package com.mrdeer.merchant.intercept;

import com.mrdeer.common.domain.BusinessException;
import com.mrdeer.common.domain.CommonErrorCode;
import com.mrdeer.common.domain.ErrorCode;
import com.mrdeer.common.domain.RestErrorResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ：xie jianchu
 * @date ：Created in 2020/9/11 0011 11:47
 */
@Slf4j
@ControllerAdvice   //与@ExceptionHandler配合使用实现全局异常处理
public class GlobalExceptionHandler {

    /**
     * 捕获Exception异常
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public RestErrorResponse processException(HttpServletRequest request, HttpServletResponse response, Exception e) {
        //异常处理
        //如果是系统自定义异常，直接取出errCode和errMessage
        if (e instanceof BusinessException) {
            log.info("BusinessException:" + e.getMessage());
            //解析系统自定义异常信息
            BusinessException businessException = (BusinessException) e;
            ErrorCode errorCode = businessException.getErrorCode();
            //错误代码
            int code = errorCode.getCode();
            //错误信息
            String msg = errorCode.getDesc();
            return new RestErrorResponse(String.valueOf(code), msg);
        }
        log.error("系统异常:" + e.getMessage());
        //统一定义为99999系统未知错误
        return new RestErrorResponse(CommonErrorCode.UNKOWN.getCode() + "", CommonErrorCode.UNKOWN.getDesc());
    }
}
